<template>
  <div>
    <template>
      <el-button type="danger" style="margin-bottom:5px" @click="batchChangeState" icon="el-icon-s-release">批量禁/反禁用</el-button>
      <el-input v-model="search" size="mini" placeholder="输入关键字搜索" clearable/>
      <el-table
        :data="tableData.filter(data => !search || data.uaccount.toLowerCase().includes(search.toLowerCase())
                                                || data.uname.toLowerCase().includes(search.toLowerCase())
                                                || data.uemail.toLowerCase().includes(search.toLowerCase()))"
        style="width: 100%; padding-bottom: 3px"
        :row-class-name="tableRowClassName"
        @selection-change="handleSelectionChange"
        >
        <el-table-column type="selection" width="50" align="center"></el-table-column>
        <el-table-column prop="uid" label="序号" type="index"></el-table-column>
        <el-table-column prop="uaccount" label="账号" width="180" sortable>
          <template slot-scope="scope">
            <el-popover trigger="hover" placement="top">
              <el-descriptions title="用户信息:" :column="2" border>
                <el-descriptions-item label="账号" content-class-name="my-content">{{ scope.row.uaccount }}</el-descriptions-item>
                <el-descriptions-item label="姓名"><el-tag size="medium">{{ scope.row.uname }}</el-tag></el-descriptions-item>
                <el-descriptions-item label="邮箱">{{ scope.row.uemail }}</el-descriptions-item>
                <el-descriptions-item label="积分">{{ scope.row.uintegral }}</el-descriptions-item>
                <el-descriptions-item label="备注">{{ scope.row.uremarks }}</el-descriptions-item>
              </el-descriptions>
              <div slot="reference" class="name-wrapper">
                <el-tag size="medium">{{ scope.row.uaccount }}</el-tag>
              </div>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column prop="uname" label="姓名" width="120" sortable>
          <template slot-scope="scope">
            <div slot="reference" class="name-wrapper">
              <el-tag size="medium" type="success">{{ scope.row.uaccount }}</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="ugender" label="性别" width="80"></el-table-column>
        <el-table-column prop="uintegral" label="积分" width="120"></el-table-column>
        <el-table-column prop="uemail" label="邮箱" width="200"></el-table-column>
        <el-table-column prop="uregtime" label="注册时间" width="200" sortable>
          <template slot-scope="scope">
            <i class="el-icon-time"></i>
            <span style="margin-left: 10px">{{scope.row.uregtime | formatDate("yyyy-mm-dd h:mi:s")}}</span>
          </template>
        </el-table-column>
        <el-table-column label="禁用状态" align="center" prop="udelete">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.udelete" @change="changeState(scope.row.uid, scope.row.udelete)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" active-value="1" inactive-value="0" @click="handleView(scope.$index, scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="pagination.pageNum"
          :page-sizes="[5, 10, 50, 100]"
          :page-size.sync="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.count">
        </el-pagination>
      </div>
    </template>
    <user-info v-if="dialogInfoVisible" :title="title" :user="user" :dialogVisible="dialogInfoVisible" @successCallback="successCallback"/>
  </div>
</template>

<script>
import Sortable from "sortablejs"
import execute from "../../utils/constant/execute"
import users from "../../api/apis/user/users"
import UserInfo from "./userInfo"
import stateCode from "../../utils/constant/stateCode"

export default {
  name: "userTable",
  components: {UserInfo},
  data () {
    return {
      tableData: [],
      pagination: { pageNum: 1, pageSize: 5, count: 100 },
      search: "",
      dialogInfoVisible: false,
      title: "",
      user: {},
      operationdisabled: false
    }
  },
  methods: {
    handleView (index, row) {
      this.$message({ showClose: true, message: "查看用户详情", row, type: execute.SUCCESS })
      users.fetchGetUsersById(row.uid).then((res) => {
        this.user = res.data.data
        this.dialogInfoVisible = true
      })
      this.title = "用户详情"
    },
    handleSelectionChange (val) {
      this.multipleSelection = val
    },
    successCallback () {
      this.loadData()
      this.dialogInfoVisible = false
    },
    changeState (uid, udelete) {
      let formData = { "uid": uid, "udelete": udelete }
      users.fetchEditUsers(formData).then((res) => {
        if (res.data.code === stateCode.OPRATION_SUCCESS) {
          this.$message({ type: execute.SUCCESS, message: res.data.msg })
        } else {
          this.$message({ type: execute.WARNING, message: res.data.msg })
        }
      }).catch((error) => {
        console.log(error)
      })
    },
    filterTag (value, row) {
      return row.tag === value
    },
    handleSizeChange (pageSize) {
      let params = new FormData()
      params.append("pageNum", 1)
      params.append("pageSize", pageSize)
      this.loadData(params)
    },
    handleCurrentChange (pageNum) {
      let params = new FormData()
      params.append("pageNum", pageNum)
      this.loadData(params)
    },
    tableRowClassName ({row}) {
      return row.udelete ? "lock" : ""
    },
    batchChangeState () {
      this.$confirm("请谨慎批量禁/反禁用操作, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: execute.WARNING,
        center: true
      }).then(() => {
        users.fetchBatchChangeState(this.multipleSelection).then((res) => {
          if (res.data.code === stateCode.OPRATION_SUCCESS) {
            this.$message({ type: execute.SUCCESS, message: res.data.msg })
          } else {
            this.$message({ type: execute.INFO, message: res.data.msg })
          }
          this.loadData()
        }).catch((res) => {
          this.$message({
            showClose: true,
            message: res.data.msg,
            type: execute.ERROR
          })
        })
      }).catch((res) => {
        this.$message({
          showClose: true,
          message: res.data.msg,
          type: execute.ERROR
        })
      })
    },
    loadData (params) {
      params = new FormData()
      if (this.pagination.pageNum !== undefined && this.pagination.pageSize !== undefined) {
        params.append("pageNum", this.pagination.pageNum)
        params.append("pageSize", this.pagination.pageSize)
      }
      users.fetchGetUsersByPage(params).then((res) => {
        this.pagination.pageNum = res.data.data.pageNum
        this.pagination.count = res.data.data.count
        this.tableData = res.data.data.result
      })
    }
  },
  filters: {
    formatDate (date, pattern) {
      var dt = new Date(date)
      var y = dt.getFullYear()
      var m = (dt.getMonth() + 1).toString().padStart(2, "0")
      var d = dt.getDate().toString().padStart(2, "0")
      var h = dt.getHours().toString().padStart(2, "0")
      var mi = dt.getMinutes().toString().padStart(2, "0")
      var s = dt.getSeconds().toString().padStart(2, "0")
      if (pattern.toLowerCase() === "yyyy-mm-dd") {
        return `${y}-${m}-${d}`
      } else {
        return `${y}-${m}-${d} ${h}:${mi}:${s}`
      }
    }
  },
  created () {
    this.loadData()
  },
  mounted () {
    let el = document.querySelectorAll(
      ".el-table__body-wrapper > table > tbody"
    )[0]
    this.sortable = Sortable.create(el)
  }
}
</script>

<style>
.sortable-ghost {
  opacity: 0.9;
}
.sortable-ghost td {
  border-top: 1px dashed #666666 !important;
  border-bottom: 1px dashed #666666 !important;
  color: #fff !important;
}
.sortable-ghost td:first-child {
  border-left: 1px dashed #666666 !important;
}
.sortable-ghost td:last-child {
  border-right: 1px dashed #666666 !important;
  border-bottom: 1px dashed #666666 !important;
}
.my-content {
  background: #FDE2E2;
}
.el-table .lock {
  background: rgb(255, 214, 214);
}
</style>
<style lang="scss">
p.dragtabe {
  margin-top: 30px;
}
</style>
